<!DOCTYPE html>
<html lang="zh">

<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>电商书库查询</title>
   <link rel="stylesheet" type="text/css" href="../css/style.css" />
   <link rel="stylesheet" type="text/css" href="../css/normalize.css" />
   <link rel="stylesheet" type="text/css"
      href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
   <!--ssMenu CSS-->
   <link rel="stylesheet" href="../css/ss-menu.css">
   <script src="../js/login.js"></script>
   <script src="../js/jquery-3.6.0.min.js"></script>
   <script src="../js/cookies.js"></script>

</head>

<body>
   <header>
      <div class="headLeft"></div>
      <div class="headMid">
         <h2>欢迎来到电商书库！</h2>
      </div>
      <div class="headRight"></div>
      <script>
         const user = getCookie("username");
         const headRight = document.querySelector(".headRight")
         headRight.innerHTML = `<p id="user">用户：${user} </p><p id="exit">退出</p>`;
         const timerIdExit = setTimeout(() => {
            // 点击退出
            exit.onclick = function () {
               // 不清楚是否实现删除cookie
               deleteCookie("login");
               window.location.href = "./login.html"
               clearTimeout(timerIdExit)
            };

         }, 200);
      </script>
   </header>
   <!--Start Side Sticky Menu-->
   <nav class="ss-menu ">
      <ul>
         <!--  -->
      </ul>
   </nav>
   <!--End Side Sticky Menu-->

   <main>
      <!-- 轮播图 -->
      <div id="banner">
         <div class="banner">
            <ul class="imgBox clearFix">

            </ul>

            <!-- 指示器存放处 -->
            <ol class="pointBox"></ol>

            <p class="leftTabs">
               <a href="javascritp:;" class="left">
                  < </a> </p> <p class="rightTabs">
                     <a href="javascritp:;" class="right"> > </a>
            </p>
         </div>
         <div class="hot">
            <h3>热门书籍</h3>
            <ol></ol>
         </div>
      </div>

      <script>
         // 获取数据并渲染轮播图
         function getData() {
            $(function () {
               $.ajax({
                  url: "/juhex",
                  type: "get",
                  data: {
                     key: "2bc8a50ea57d7cc2673d74e21e6aea2a", //
                     catalog_id: 242,
                     pn: 0,
                     rn: 30
                  },
                  success: function (dataObj, status, xhr) {
                     const arrData = dataObj.result.data;
                     arrData.sort(function (a, b) {
                        return (parseInt(b.reading) - parseInt(a.reading))
                     });

                     const imgBox = banner.querySelector(".banner .imgBox")

                     let tempStr1 = ""
                     let countLength1;
                     if (arrData.length < 5) {
                        countLength1 = arrData.length
                     } else {
                        countLength1 = 5
                     }
                     for (let i = 0; i < countLength1; i++) {
                        tempStr1 += `<li>
                        <a href="./details.html?messages=${encodeURI(arrData[i].title)}/.${encodeURI(arrData[i].catalog)}/.${encodeURI(arrData[i].tags)}/.${encodeURI(arrData[i].sub1)}/.${encodeURI(arrData[i].sub2)}/.${encodeURI(arrData[i].img)}/.${encodeURI(arrData[i].reading)}/.${encodeURI(arrData[i].online)}/.${encodeURI(arrData[i].bytime)}/" target="_blank" >
                        <img src="${arrData[i].img}"
                        alt="" />
                        </a>
                        </li>`
                     }
                     imgBox.innerHTML = tempStr1;
                  },
                  error: function (xhr, status, err) {
                     $('#main').html(err.toString());
                     // 
                  },
               });
            });
         }
         getData()
         // 获取数据并渲染排行榜
         function getData1(pn, rn, id = 242) {
            $(function () {
               $.ajax({
                  url: "/juhex",
                  type: "get",
                  data: {
                     key: "2bc8a50ea57d7cc2673d74e21e6aea2a", //
                     catalog_id: id,
                     pn: pn,
                     rn: rn
                  },
                  success: function (dataObj, status, xhr) {
                     const arrData = dataObj.result.data;
                     arrData.sort(function (a, b) {
                        return (parseInt(b.reading) - parseInt(a.reading))
                     });

                     // console.log(arrData);


                     const hotOls = banner.querySelector(".hot ol");
                     let tempStr2 = "";

                     // 判断标签下的数据是否够10条
                     let countLength2;
                     if (arrData.length < 10) {
                        countLength2 = arrData.length
                     } else {
                        countLength2 = 10
                     }

                     for (let i = 0; i < countLength2; i++) {
                        tempStr2 += `<li>
                        <a href="./details.html?messages=${encodeURI(arrData[i].title)}/.${encodeURI(arrData[i].catalog)}/.${encodeURI(arrData[i].tags)}/.${encodeURI(arrData[i].sub1)}/.${encodeURI(arrData[i].sub2)}/.${encodeURI(arrData[i].img)}/.${encodeURI(arrData[i].reading)}/.${encodeURI(arrData[i].online)}/.${encodeURI(arrData[i].bytime)}/" target="_blank" >
                        《${arrData[i].title}》
                        </a>
                        </li>`
                     }
                     hotOls.innerHTML = tempStr2;
                     // return arrData;
                  },
                  error: function (xhr, status, err) {
                     $('#main').html(err.toString());
                     // 
                  },
               });
            });
         }
         getData1(0, 30);
      </script>
      <script src="../js/banner.js"></script>

      <!-- 主要内容 -->
      <div id="box">
         <ul></ul>
         <ul></ul>
         <ul></ul>
         <ul></ul>
      </div>
      <script src="../js/online.js"></script>
      <script>
         // 定义起始数据中的next_start
         let start = 0;
         // 设置滚动时的开关，如果滚动得到的数据没有渲染完则不能够添加新数据
         let flag1 = false;
         // 设置数据获取开关，当最后一次获取的数据长度不足设定的rn（+28）时，不能获取数据（不设会出现数据接口无法获得不同节点的新数据）
         let flag2 = true;


         // 页面更新前的清理（因为主要内容是通过appendChild加入的，后续可修改此规则）
         function refreshMain() {
            const mainUls = document.querySelectorAll('#box ul')
            mainUls.forEach(item => {
               item.innerHTML = ""
            })
         }

         // 获取数据并渲染主要内容
         function getData2(pn, rn, id = 242) {
            if (flag1) {
               return;
            }
            flag1 = true;
            $(function () {
               $.ajax({
                  url: "/juhex",
                  type: "get",
                  data: {
                     key: "2bc8a50ea57d7cc2673d74e21e6aea2a", //
                     catalog_id: id,
                     pn: pn,
                     rn: rn
                  },
                  success: function (data, status, xhr) {
                     renderHtml2(data);
                     if (data.result.data.length < 28) {
                        flag2 = false;
                     }
                  },
                  error: function (xhr, status, err) {
                     $('#main').html(err.toString());
                     // 
                  },
               });
            });
            start += 28;
         }

         // 首次获取数据
         getData2(start, start + 28)

         // 页面更新
         const timeId2 = setTimeout(() => {
            const catalogLis = document.querySelectorAll(".ss-menu>ul li")
            const hotTitle = banner.querySelector(".hot h3")

            catalogLis.forEach(item => {
               item.onclick = function () {

                  const a = this.querySelector("a");
                  refreshMain();

                  start = 0;

                  getData1(0, 30, a.id);


                  getData2(start, start + 27, a.id)

               }
            })
            clearTimeout(timeId2)
         }, 500);


         // 将获取到的数据进行渲染
         function renderHtml2(dataObj) {
            const arr = dataObj.result.data;

            // 每次遍历数据中的对象清单，将里面相关内容添加进将要渲染的li中
            arr.forEach(item => {
               const li = document.createElement('li');
               // 该数据有误
               if (item.title === "1984") {
                  return;
               }
               li.innerHTML = `<a href="./details.html?messages=${encodeURI(item.title)}/.${encodeURI(item.catalog)}/.${encodeURI(item.tags)}/.${encodeURI(item.sub1)}/.${encodeURI(item.sub2)}/.${encodeURI(item.img)}/.${encodeURI(item.reading)}/.${encodeURI(item.online)}/.${encodeURI(item.bytime)}/" target="_blank" >
                    <img src="${item.img}"
                        alt="" />
                </a>
                <div>
                    <h5 class="bookTitle">《${item.title}》</h5>
                    <div class="bookCatalog">     
                        类别：${item.catalog}
                    </div>
                    <div class="onlineShop">在线商城：
                        ${generateOnline(item.online)}
                     </div>
                    <div class="moreInfo">
                        <div class="readers">
                           <span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span>
                           <span>&nbsp;&nbsp;${item.reading}</span>
                        </div>
                        <div class="bytime">
                            <span>${item.bytime}</span>
                        </div>
                    </div>
                </div>`

               getShortest().appendChild(li);
            });
            flag1 = false;
         }

         // 排版规则为1 2 3 4,4个ul谁最短，在其下方添加li
         // 此处有点bug
         function getShortest() {
            const uls = document.querySelectorAll('#box>ul');
            let shortestUl = uls[0];
            let shortestUlHeight = uls[0].clientHeight;
            uls.forEach(ul => {
               if (ul.clientHeight < shortestUlHeight) {
                  shortestUl = ul;
                  shortestUlHeight = ul.clientHeight;
               }
            })
            return shortestUl;
         }
         // 滚动时判断最短的ul是不是比滚动长度与目前页面长度之和小，小了则为数据不够，需要添加新的数据了
         window.onscroll = function () {
            // 滑动获取数据开关
            if (!flag2) {
               return;
            }
            if (document.documentElement.scrollTop + document.documentElement.clientHeight > getShortest()
               .clientHeight) {
               getData2(start, start + 27);
            }

         }
      </script>
   </main>
   <aside>
      <div class="goTop">☝</div>
   </aside>
   <!-- 返回顶部 -->
   <script>
      $(window).scroll(function () {
         if ($(this).scrollTop() >= 100) {
            $('.goTop').show()
         } else {
            $('.goTop').hide()

         }
      })

      $('.goTop').on('click', function () {
         $('html').animate({
            scrollTop: 0
         }, 1000, 'linear')
      })
   </script>
   <!-- 添加导航栏 -->
   <script>
      $(function () {
         $.ajax({
            url: "/juhe",
            // url: "../static/catalog.json",
            type: "get",
            // data: {  key: "2bc8a50ea57d7cc2673d74e21e6aea2a" },
            data: {key: "2bc8a50ea57d7cc2673d74e21e6aea2a"},
            dataType:"json",
            success: function (data, status, xhr) {
               renderHtml1(data);
            },
            error: function (xhr, status, err) {
               $('#main').html(err.toString());
            },
         });
      });

      function renderHtml1(dataObj) {
         const arr = dataObj.result;
         let count = 0;
         // 每次遍历数据中的对象清单，将里面相关内容添加进将要渲染的li中
         arr.forEach(item => {
            const li = $(`<li><a href="#1" id="${item.id}"><i class="fa"></i> ${item.catalog}</a></li>`);
            const uniLi = $(
               `<li id="more">
                     <a href="#1" >
                        <i class="fa">                          
                        </i>
                         更多分类
                     </a>
                     <ul id="secondNav"></ul>

                  </li>`
            );
            count++;
            if (count === 10) {
               $('.ss-menu ul').append(uniLi);
               return;
            }
            if (count > 10) {
               $('.ss-menu ul #more #secondNav').append(li);
               return;
            }
            $('.ss-menu ul').append(li);
         });
      }
   </script>

   <script src="../js/jquery.ss.menu.js"></script>
   <script>
      // 滑出功能的顺序
      $(document).ready(function () {

         $(".ss-menu").ssMenu();

      });
   </script>
   <script>
      // 导航栏滑出功能
      $(function () {
         var ssMenu = $(".ss-menu");
         var theme = $(".theme-picker").find("span");

         $(theme).click(function (y) {

            y = $(this).attr("class");

            $(ssMenu).removeClass().addClass("ss-menu " + y);
         });

         $(".set-default").click(function () {
            $(ssMenu).removeClass().addClass("ss-menu default");

         });

      });
   </script>
   <script>
      // 找到js创建的导航栏更多标签

      const timeId1 = setTimeout(() => {
         const secondTrg = $('.ss-menu>ul>#more')
         $(secondTrg).mouseenter(function () {
            $(this).css({
               "overflow": "visible"
            }).find('#secondNav').show()

         });
         $(".ss-menu>ul").mouseleave(function () {
            $(secondTrg).css({
               "overflow": "hidden"
            }).find('#secondNav').hide()
            clearTimeout(timeId1)
         });

      }, 500);
   </script>
</body>

</html>